package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.CompanySummary;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;

import retrofit2.Call;

public class MemberAddActivity extends AppCompatActivity {

    private String orgid = "";
    private TextView orgtitle;
    private TextView role;
    Button nextBtn;
    ProgressDialog progressDialog;
    private CheckBox isfreeCbox ;

    Integer ORG_CODE =  234;
    Integer SEARCH_CODE =  123;
    private String from ="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_add);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
        nextBtn = (Button) findViewById(R.id.member_add_save);


        Intent intent = getIntent();

        this.setTitle("添加组织身份");


        orgtitle = (TextView)findViewById(R.id.my_org_edit_title);
        role = (TextView)findViewById(R.id.my_role);

        orgtitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus){
                    Intent intent = new Intent();
                    intent.putExtra("content", orgtitle.getText().toString());

                    intent.setClass(MemberAddActivity.this,  FilterCompany.class);
                    startActivityForResult(intent,SEARCH_CODE);
                }
            }
        });



        orgtitle.setFocusable(true);
        orgtitle.setFocusableInTouchMode(true);
        orgtitle.requestFocus();
        MemberAddActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);





        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    if (orgtitle.getText().toString().equals("")) {
                        Common.alert(MemberAddActivity.this, "请输入企业/机构名称");
                        orgtitle.setFocusable(true);
                        orgtitle.setFocusableInTouchMode(true);
                        orgtitle.requestFocus();
                        return;
                    }

                    if (role.getText().toString().equals("")) {
                        Common.alert(MemberAddActivity.this, "请输入你的职务");
                        role.setFocusable(true);
                        role.setFocusableInTouchMode(true);
                        role.requestFocus();
                        return;
                    }

                    addMember();
            }
        });

    }


    private void addMember( ){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在添加新身份······");
        progressDialog.show();

        final String thetitle = orgtitle.getText().toString();
        final String therole = role.getText().toString();
        AsyncTask<Void,Void,BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.addMember(WoyaoooApplication.userId,orgid,thetitle,therole);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        progressDialog.dismiss();
                        if (! response.getCondition().equals("")){
                            verifyOrg(response);
                        } else {
                            goon();
                        }
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }

    private  void goon(   ){

            Intent intent = new Intent();
            intent.putExtra("changed", true);
            setResult(666, intent);
            finish();
    }

    private void verifyOrg( final  BaseResponse br) {
        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("完善组织信息").
                setMessage("该组织信息还没有完善和认证，现在完善信息").
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.putExtra("from", from);
                        intent.putExtra("id", Integer.parseInt( br.getCondition()));
                        intent.setClass(MemberAddActivity.this, OrgActivity.class);
                        startActivityForResult(intent, ORG_CODE);
                    }
                }).
                setNegativeButton("暂不", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goon();
                    }
                }).
                create();
        alertDialog.show();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", false );
        setResult(666, intent);
        finish();
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == SEARCH_CODE  ) {
            CompanySummary cs  = (CompanySummary)data.getExtras().get("data");
            if (cs == null )
                return;
            orgid = cs.getId();
            if ( !orgid.equals("0") ) {
                orgtitle.setText(cs.getTitle());
            }
        }
        if(requestCode == ORG_CODE  ) {

            Intent intent = new Intent();
            intent.putExtra("changed", true );
            setResult(666, intent);
            finish();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", false );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


}
